/*
https://flutter.cn/docs/get-started/flutter-for/android-devs

如何显示验证错误的信息？
就像上面实现「提示」功能一样，像 Text Widget 构造方法的 decoration 参数传入一个 InputDecoration 对象。

然而，你并不想一开始就显示错误信息。相反，当用户输入了无效的信息后，更新状态并传入一个新的 InputDecoration 对象


 */

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const SampleAppPage(),
    );
  }
}

class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});

  @override
  State<StatefulWidget> createState() => _SampleAppPageState();
}

class _SampleAppPageState extends State<SampleAppPage> {
  String? _errorText;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Sample App'),),
      body: Center(
        child: TextField(
          onSubmitted:(text) {
            setState(() {
              if(!isEmail(text)){
                _errorText = 'Error: This is not an email';
              }else{
                _errorText = null;
              }
            });
          },
          decoration: InputDecoration(hintText: 'This is a hint',errorText: _getErrorText()),
        ),
      ),
    );
  }

  String? _getErrorText() {
    return _errorText;
  }

  bool isEmail(String em) {
    String emailRegexp =
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|'
        r'(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|'
        r'(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
    RegExp regExp = RegExp(emailRegexp);
    return regExp.hasMatch(em);
  }
}